package com.bnd.utils;

import org.springframework.web.multipart.MultipartFile;
import javax.sound.sampled.*;
import java.io.IOException;

public class AudioFileValidator {
    
    // 支持的音频格式
    private static final String[] SUPPORTED_FORMATS = {".wav", ".mp3", ".m4a"};
    
    // 音频参数限制
    private static final int MIN_SAMPLE_RATE = 16000;
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    private static final int MIN_DURATION = 10; // 10秒
    private static final int MAX_DURATION = 60; // 60秒
    private static final int RECOMMENDED_DURATION = 20; // 20秒
    
    /**
     * 校验音频文件
     * @param file 音频文件
     * @throws IllegalArgumentException 校验失败时抛出异常
     */
    public static void validateAudioFile(MultipartFile file) throws IllegalArgumentException {
        // 1. 文件大小校验
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("文件大小超过10MB限制");
        }
        
        // 2. 文件格式校验
        String fileName = file.getOriginalFilename();
        if (fileName == null || !isSupportedFormat(fileName)) {
            throw new IllegalArgumentException("不支持的音频格式，仅支持WAV、MP3、M4A格式");
        }
        
        // 3. WAV文件额外校验（采样率、声道数）
        if (fileName.toLowerCase().endsWith(".wav")) {
            validateWavFile(file);
        }
    }
    
    /**
     * 检查是否为支持的格式
     * @param fileName 文件名
     * @return 是否支持
     */
    private static boolean isSupportedFormat(String fileName) {
        String lowerFileName = fileName.toLowerCase();
        for (String format : SUPPORTED_FORMATS) {
            if (lowerFileName.endsWith(format)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 校验WAV文件参数
     * @param file WAV文件
     * @throws IllegalArgumentException 校验失败时抛出异常
     */
    private static void validateWavFile(MultipartFile file) throws IllegalArgumentException {
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file.getInputStream());
            AudioFormat format = audioInputStream.getFormat();
            
            // 校验采样率
            float sampleRate = format.getSampleRate();
            if (sampleRate < MIN_SAMPLE_RATE) {
                throw new IllegalArgumentException("采样率低于16000Hz要求");
            }
            
            // 校验声道数（1或2声道）
            int channels = format.getChannels();
            if (channels != 1 && channels != 2) {
                throw new IllegalArgumentException("声道数必须为单声道或双声道");
            }
            
            // 校验位深度（16bit）
            int bitDepth = format.getSampleSizeInBits();
            if (bitDepth != 16) {
                throw new IllegalArgumentException("WAV文件必须为16bit格式");
            }
            
            // 估算时长
            long frameLength = audioInputStream.getFrameLength();
            if (frameLength != AudioSystem.NOT_SPECIFIED) {
                double duration = frameLength / sampleRate;
                if (duration < MIN_DURATION) {
                    throw new IllegalArgumentException("音频时长少于10秒");
                }
                if (duration > MAX_DURATION) {
                    throw new IllegalArgumentException("音频时长超过60秒");
                }
            }
            
            audioInputStream.close();
        } catch (UnsupportedAudioFileException e) {
            throw new IllegalArgumentException("不支持的音频文件格式");
        } catch (IOException e) {
            throw new IllegalArgumentException("音频文件读取失败");
        }
    }
}
